package com.easyban.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyban.common.BaseContext;
import com.easyban.common.R;
import com.easyban.dto.OrdersDto;
import com.easyban.dto.UserDto;
import com.easyban.entity.Orders;
import com.easyban.entity.OrdersDetail;
import com.easyban.entity.User;
import com.easyban.entity.UserAddress;
import com.easyban.service.OrdersDetailService;
import com.easyban.service.OrdersService;
import com.easyban.service.UserAddressService;
import com.easyban.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/orders")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersDetailService ordersDetailService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private UserService userService;

    @PostMapping
    public R<String> addOrderDto(@RequestBody OrdersDto ordersDto) {
        //核对地址和用户id是否是同一个人的
        User user = userService.getById(BaseContext.getCurrentId());
        ordersDto.setUserId(BaseContext.getCurrentId());
        ordersDto.setStatus(0);

        LambdaQueryWrapper<UserAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAddress::getUserId, user.getUserId());
        queryWrapper.eq(UserAddress::getId, ordersDto.getAddressId());

        int count = userAddressService.count(queryWrapper);
        if (count > 0) {
            ordersService.addOrderDto(ordersDto);
            return R.success("购买成功");
        }
        else return R.error("地址填写失误");
    }

    @GetMapping("/page")
    private R<Page<OrdersDto>> page(int page, int pageSize, String orderId, String userId) {
        log.info("执行分页查询....");
        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNoneEmpty(orderId) && StringUtils.isNoneEmpty(userId)) {
            queryWrapper.eq(Orders::getId, orderId);
            queryWrapper.eq(Orders::getUserId, userId);
        } else if (StringUtils.isNoneEmpty(orderId)) {
            queryWrapper.eq(Orders::getId, orderId);
        } else if (StringUtils.isNoneEmpty(userId)) {
            queryWrapper.eq(Orders::getUserId, userId);
        }
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getCreateTime);

        ordersService.page(pageInfo, queryWrapper);

        List<Orders> records = pageInfo.getRecords();

        List<OrdersDto> ordersDtos = new ArrayList<>();

        for (Orders record : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record, ordersDto);
            ordersDtos.add(ordersDto);
            log.info(ordersDto.toString());
        }

        for (OrdersDto ordersDto : ordersDtos) {
            LambdaQueryWrapper<OrdersDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrdersDetail::getOrdersId, ordersDto.getId());
            List<OrdersDetail> list = ordersDetailService.list(queryWrapper1);
            ordersDto.setOrdersDetailList(list);
        }
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, ordersDtoPage);
        ordersDtoPage.setRecords(ordersDtos);

        return R.success(ordersDtoPage);
    }

    @PutMapping("/setStatus")
    public R<String> setStatus(@RequestParam String id, @RequestParam Integer status) {
        Orders orders = ordersService.getById(id);
        orders.setStatus(status);
        ordersService.updateById(orders);
        return R.success("修改成功");
    }

    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Long id) {
        Orders orders = ordersService.getById(id);
        if (orders.getStatus() != 4) return R.error("未确认收货，不能删除");

        LambdaQueryWrapper<OrdersDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrdersDetail::getOrdersId, id);
        ordersDetailService.remove(queryWrapper);

        ordersService.removeById(id);

        return R.success("删除成功");
    }
}
